import os

from django.shortcuts import render
from django.http import HttpResponse, FileResponse, JsonResponse
import json
from index.utils import insert, reinit, search, open_folder, set_folder_path, gen_pages
import math
def page_search(request):
    return render(request, 'search.html')


def page_result(request):
    pass


def api_search(request):
    if request.method == "POST":
        keyword = request.POST.get('keyword').strip()
        page = int(request.POST.get('page'))
        page_items = 10
        show_pages = 10

        res = search(keyword)
        if len(res) == 0:
            context = {"info": "查询结果为0"}
            return render(request, 'result.html', context=context)

        total_page = math.ceil(len(res) / page_items)
        res = res[(page-1)*page_items: page*page_items]

        context = {"meetings": list(), "keyword": keyword }
        for meeting in res:
            content = join_strings(meeting["files"])
            title = meeting["meeting_name"]
            context["meetings"].append({"content": content, "title": title})

        context["pages"] = gen_pages(page, total_page, show_pages)
        context["pre_state"] = ""
        context["aft_state"] = ""
        if context["pages"][0] == 1:
            context["pre_state"] = "disabled"
        if context["pages"][-1] == total_page:
            context["aft_state"] = "disabled"
        context["curr_page"] = page


        context["data"] = json.dumps({
            "curr_page": page,
            "total_page": total_page,
            "keyword": keyword
        })

        return render(request, 'result.html', context=context)


def api_insert(request):
    if request.method == "POST":
        data = json.loads(request.body)
        folder_name = data["folder_name"].strip()

        response = HttpResponse()

        try:
            insert(folder_name)
        except Exception as e:
            response.status_code = 400
            return response

        response.status_code = 200
        return response


def api_reinit(request):
    if request.method == "POST":
        response = HttpResponse()
        try:
            reinit()
            response.status_code = 200
        except Exception as e:
            response.status_code = 400
            raise e

        return response


def api_open_folder(request):
    if request.method == "POST":
        data = json.loads(request.body)
        folder_name = data["folder_name"].strip()

        open_folder(folder_name)

        return HttpResponse()


def join_strings(list_of_strings):
    new_list = []
    for s in list_of_strings:
        if not s.startswith("《") and not s.endswith("》"):
            s = "《" + s + "》"
        new_list.append(s)
    return "".join(new_list)


def page_setting(request):
    return render(request, 'setting.html')


def api_folder_path(request):
    if request.method == "POST":
        data = json.loads(request.body)
        folder_path = data["folder_path"]

        state = set_folder_path(folder_path)

        if state:
            response = JsonResponse({"info": "成功设置文件夹根目录地址为  "+folder_path})
        else:
            response = JsonResponse({"error": "路径不合法，上传失败"}, status=400)

        return response

